import entity.RpcRequest;
import entity.RpcResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class WorkThread implements Runnable{
    private Socket client;
    private Object service;

    public WorkThread(Socket client, Object service){
        this.client = client;
        this.service = service;
    }

    @Override
    public void run() {
        System.out.println("server 开始处理请求");
        try(ObjectInputStream inputStream = new ObjectInputStream(client.getInputStream());
            ObjectOutputStream outputStream = new ObjectOutputStream(client.getOutputStream())){
            System.out.println("reading request ...");
            RpcRequest request =  (RpcRequest) inputStream.readObject();
            System.out.println("client wants : "+request.getInterfaceName());
            System.out.println("client wants : "+request.getMethodName());
            //拿到请求要执行的方法
            Method method = service.getClass().getMethod(request.getMethodName(), request.getParamTypes());

            Object res = method.invoke(service, request.getParameters());
            outputStream.writeObject(RpcResponse.success(res));
            outputStream.flush();
            System.out.println("服务器处理完成！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
